<template>
    <div>
        <!--  -->
       <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>添加商品</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
             <!--警告提示的文案  -->
        <el-alert title="温馨提示：添加商品信息" center type="info" :closable="false" show-icon>
          </el-alert>

          <el-steps :space="200" :active="activeIndex-0" finish-status="success" align-center>
            <el-step title="基本信息"></el-step>
            <el-step title="商品参数"></el-step>
            <el-step title="商品属性"></el-step>
            <el-step title="商品图片"></el-step>
            <el-step title="商品内容"></el-step>
            <el-step title="完成"></el-step>
         </el-steps>
         <!-- 表单 -->
         <el-form :model="addForm" status-icon :rules="addFormRules" ref="addFormRef" label-width="100px" label-position="top" class="demo-ruleForm">
            <!-- 标签栏 -->
            <el-tabs type="border-card"  v-model='activeIndex' :tab-position="'left'" :before-leave='beforeTabLeave' @tab-click="tabClick">
                <el-tab-pane label="基本信息" name="0">
                    <el-form-item label="商品名称"   prop="goods_name">
                      <el-input  v-model="addForm.goods_name"   clearable></el-input>
                </el-form-item>
                        <!-- 邮箱 -->
                <el-form-item  prop="goods_price" label="价格(￥)" >         
                     <el-input v-model="addForm.goods_price" clearable oninput="value=value.replace(/[^\d]/g,'')"   ></el-input>
                </el-form-item>
                        <!-- 电话 -->
                <el-form-item label="数量(件)" prop="goods_number">
                      <el-input  v-model.number="addForm.goods_number" oninput="value=value.replace(/[^\d]/g,'')"
                        clearable   ></el-input>
                </el-form-item>
                <el-form-item label="重量(KG)" prop="goods_weight">
                      <el-input  v-model.number="addForm.goods_weight" oninput="value=value.replace(/[^\d]/g,'')"
                        clearable   ></el-input>
                </el-form-item>
               
                  <el-form-item label=" 选择商品分类 " prop="goods_cats">
                  
                    <el-cascader  v-model=" addForm.goods_cats" :options="cateList"  expand-trigger="hover"
                        :props="cateProps " @change="cateChanged"  clearable ></el-cascader>
                     </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品参数" name="1" >
                     <el-form>
                        <el-form-item :label="item.attr_name" v-for="(item,i) in manyData" :key="item.attr_id">
                                <el-input v-model="item.attr_vals"></el-input>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="商品属性" name="2">
                    <el-form>
                        <el-form-item :label="item.attr_name" v-for="(item,i) in onlyData" :key="item.attr_id">
                                <el-input v-model="item.attr_vals"></el-input>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="商品图片" name="3">
                    <el-upload
                            :on-success ="handleSuccess"
                            :action="uploadImgUrl"
                            :on-preview="handlePreview"
                            :on-remove="handleRemove"
                             :headers="headerObj"
                            list-type="picture">
                            <el-button size="small" type="primary">上传图片</el-button>
                            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                            </el-upload>
                </el-tab-pane>
                <el-tab-pane label="商品内容" name="4">
                    <quill-editor v-model="addForm.goods_introduce" class="queditor">
                    </quill-editor>
                    <el-button class="btnadd" type="primary" size="small" @click="addGoods">添加商品</el-button>
                </el-tab-pane>
            </el-tabs>

        </el-form>
        </el-card>

        <!-- 图片预览对话框 -->
        <el-dialog title="图片预览" :visible.sync="imgdialogVisible"  width="50%" >
               <img :src="preurl "  class="preimg">  
                 
       </el-dialog>
    </div>
</template>

<script>
import _ from 'lodash'//引入深拷贝组件
export default {
    data(){
        return{
            activeIndex:'0',
            addForm:{
                 goods_name:'',
                 goods_price:0,
                 goods_weight:0,
                 goods_number:0,
                 goods_cats:[],
                 pics:[],
                 goods_introduce:'',
                 attrs:[],
            },
            formClone:{},
            gclength:0,
            cateList:[],
            params_sel:'',
            cateProps:{
                value:'cat_id',
                label:'cat_name',
                children:'children'
            },
            manyData:[],
            onlyData:[],
            uploadImgUrl:'http://127.0.0.1:8888/api/private/v1/upload',
            //上传图片携带请求头

            headerObj:{
                Authorization:window.sessionStorage.getItem('token')
            },
            imgdialogVisible:false,
            preurl:'',
            addFormRules:{
                 goods_name:[
                    { required: true, message: '请输入商品名称', trigger: 'blur' },
                    ],
                goods_price:[
                    { required: true, message: '请输入价格', trigger: 'blur' },
                    ],
                goods_weight:[
                    { required: true, message: '请输入重量', trigger: 'blur' },
                    ],
                goods_number:[
                     { required: true, message: '请输入数量', trigger: 'blur' },
                 ],
                 goods_cats:[
                      { required: true, message: '请选择商品分类', trigger: 'blur' },
                 ]
        }
        }
    },
    created(){
        this.getCateList()
    },
    computed:{
        cateId(){
            if(this.gclength == 3){
                return this.addForm.goods_cats[2]

            }
            return null
        }
    },
    methods:{
          async getCateList(){
            const {data:res} = await this.$http.get('categories',{
                params:this.queryinfo
            })
            if(res.meta.status !== 200 ) return this.$Message.error('分类数据请求失败！')
                // this.total = res.data.total
                this.cateList = res.data 
                // console.log(this.cateList);
        },
       cateChanged(){
            this.gclength = this.addForm.goods_cats.length;
            if(this.gclength  !== 3){
                 this.addForm.goods_cats = []
            }
            // console.log(this.addForm.goods_cats);
        },

        beforeTabLeave(newActiveName,oldActiveName){
            if(this.gclength  !== 3){
                 this.addForm.goods_cats = []
                 this.$Message.info('请先选择商品分类')
                 return false
            }
            // console.log("新："+newActiveName);
            // console.log("旧："+oldActiveName);
        },
       async tabClick(){
        //    console.log(this.activeIndex);
        //    点击商品参数
           if(this.activeIndex == 1){
               this.params_sel = 'many';
               this.getParamsData()
           }else if(this.activeIndex == 2){
                this.params_sel = 'only';
                 this.getParamsData()
           }
        },
         async getParamsData(){
           const {data:res} = await this.$http.get(`categories/${this.cateId}/attributes`,{
               params:{sel:this.params_sel}
           })
           if(res.meta.status !== 200) return this.$Message.error('获取失败')
          if(this.params_sel == 'many'){
               this.manyData = res.data
          }else{
               this.onlyData = res.data
          }
        //    console.log(res);
           this.$Message.success('获取成功')
        },
        // 图片预览效果事件3
        handlePreview(file){
           this.preurl = file.response.data.url;
            this.imgdialogVisible =true;
        },
        // 移除图片
        handleRemove(file){
           const filePath =  file.response.data.tem_path
         const i =  this.addForm.pics.findIndex(
               x => x.pic == filePath
           )
           this.addForm.pics.splice(i,1)
        },
        // 监听上传成功事件
        handleSuccess(response){
            this.addForm.pics.push(response.data.tmp_path);
            console.log(this.addForm);
        },
        addGoods(){
            this.$refs.addFormRef.validate(async valid =>
            {
                if(!valid) return this.$Message.info('请填写必要的表单项')

            })
            // 添加商品请求
            this.formClone = _.cloneDeep(this.addForm)

           this.formClone.goods_cats =   this.formClone.goods_cats.join(',')
        //    合并动态参数和静态属性
        this.manyData.forEach(item=>{
            const newinfo = {
                attr_id: item.attr_id,
                attr_value: item.attr_value.join(' ')
            }
            this.addForm.attrs.push(newinfo)
        })

        this.onlyData.forEach(item=>{
            const newinfo ={
                  attr_id: item.attr_id,
                attr_value: item.attr_value.join(' ')
            }
             this.addForm.attrs.push(newinfo)
        })
        this.formClone.attrs =  this.addForm.attrs
           console.log( this.formClone);
        //  const {data:res} = await  this.$http.post(`goods`,)
        }

    }
}
</script>

<style lang="less" scoped>
.el-card, .el-alert,.el-row {
    margin:10px 0px;
    box-shadow: 0 0 3px #ddd;
}
.el-breadcrumb{
    margin-bottom:15px;
}
.el-steps{
    margin:20px 0px;
}
.preimg{
    width: 100%;

}
 
.btnadd{
    margin-top: 15px;
}
</style>